using System;
using System.Collections.Generic;
using SimpleJSON;
using UnityEngine;

namespace Gj.DarkLoong
{
    public class Leaderboard
    {
        public static Dictionary<string, JSONArray> ListCache = new Dictionary<string, JSONArray>() {};
        public static Dictionary<string, int> NumberCache = new Dictionary<string, int>() {};

        public static void List(string identity, int limit, Action<JSONArray, JSONObject> callback)
        {
            Debug.Log($"list leaderboard: {identity} {limit} {Auth.IsLogin()}");
            if (!Auth.IsLogin()) return;
            // identity = identity.Replace("-", "_");
            // if (ListCache.TryGetValue(identity, out var result))
            // {
            //     // 有缓存直接读取缓存
            //     callback(result, NumberCache[identity]);
            //     return;
            // }
            Project.ProjectUpdate.Queue.Enqueue(async () =>
            {
                Debug.Log($"list leaderboard: {identity} {limit}");
                var data = new JSONObject();
                data["fields"] = "nick_name,avatar,id";
                data["limit"] = $"{limit}";
                data["start"] = "0";
                var header = Api.CookieHeader();
                header["token"] = Auth.SessionToken;
                var scorePageResponse = await Api.Get($"/workshop/leaderboard/{identity}/rank", data, header);

                var info = new JSONArray();
                var result = scorePageResponse["result"];
                foreach (var one in result["list"].AsArray.Children)
                {
                    var item = new JSONObject();
                    item["score"] = one["value"];
                    item["userId"] = one["user"]["id"];
                    item["rank"] = one["rank"].AsInt;
                    item["nickName"] = one["user"]["nick_name"];
                    info.Add(item);
                }

                // ListCache[identity] = info;
                // NumberCache[identity] = rank;
                callback(info, result["self"].AsObject);
            });

        }
    }
}